/*******************************************************************************
 * Copyright (c) 2009-2011 ETCORE Labs. All rights reserved. 
 * 
 * This software is the confidential and proprietary information of ETCORE Labs.
 * You shall not disclose such confidential information and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with ETCORE Labs. 
 * 
 * Support can be obtained from support forums at:  http://www.etcore.com/
 * /
 *******************************************************************************/
package etcore.webapp.grouptalk.user.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import etcore.webapp.grouptalk.common.action.AbstractAction;
import etcore.webapp.grouptalk.common.config.Config;
import etcore.webapp.grouptalk.common.config.MessageNamespaces;
import etcore.webapp.grouptalk.common.config.Messages;
import etcore.webapp.grouptalk.common.config.PageConstants;
import etcore.webapp.grouptalk.common.object.Attachment;
import etcore.webapp.grouptalk.common.object.Comment;
import etcore.webapp.grouptalk.common.object.Message;
import etcore.webapp.grouptalk.common.service.AttachmentService;
import etcore.webapp.grouptalk.common.service.MessageService;
import etcore.webapp.grouptalk.user.object.User;
import etcore.webapp.grouptalk.util.Symbols;

/**
 * This action validates the request and executes the command of getting my
 * messages,then set the corresponding attributes for output
 * 
 * @author ETCORE GroupTalk Developers
 * 
 */
public class MyMessagesAction extends AbstractAction {

	private static final long serialVersionUID = 4599787097897244199L;
	// validate result
	public static final int ACCESS_ALLOWED = 0;
	public static final int ERROR = 1;
	public static final int REMOVE_ALLOWED = 2;
	// utility constants

	public static final String START_PID = "startpid";
	public static final String END_PID = "endpid";
	public static final String COMMENT_NUM = "commentNum";
	public static final String LAST_COMMENT = "lastComment";
	public static final String KEY = "key";
	public static final String DEFAULT_OPEN = "2";
	public static final String COMMUNITIES_MSG_SIZE = "communitiesMsgSize";
	public static final String BOOKMARKS_MSG_SIZE = "bookmarksMsgSize";
	public static final String REMINDERS_MSG_SIZE = "remindersMsgSize";
	public static final String INFO_MSG_SIZE = "infoMsgSize";
	public static final String NAV1_MSG_SIZE = "nav1MsgSize";
	public static final String NAV2_MSG_SIZE = "nav2MsgSize";
	public static final String REMOVE_MESSAGE = "removeMessage";

	@Override
	public int validate(HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession(true);

		String cmd = request.getParameter(PageConstants.CMD);
		User sessionUser = (User) session.getAttribute(Messages.SESSION_USER);
		if (sessionUser != null && REMOVE_MESSAGE.equals(cmd))
			return REMOVE_ALLOWED;
		else if (sessionUser != null)
			return ACCESS_ALLOWED;
		return ERROR;

	}

	@Override
	public String getForward(HttpServletRequest request, int validationResult) {
		if (ERROR == validationResult)
			return PageConstants.ACTION_PATH_ERROR;
		else if (REMOVE_ALLOWED == validationResult) {
			String open = request.getParameter(PageConstants.OPEN);
			if (open != null)
				return PageConstants.PAGE_ACTION_MYINFO
						+ "?init=myMessages&open=" + open;
			else
				return PageConstants.PAGE_ACTION_MYINFO + "?init=myMessages";
		}
		return PageConstants.PAGE_PATH_MYMESSAGES;
	}

	@Override
	public String getRedirect(HttpServletRequest request, int validationResult) {
		// TODO Auto-generated method stub

		return null;
	}

	@Override
	public void execute(int validationResult, HttpServletRequest request,
			HttpServletResponse response) {
		if (REMOVE_ALLOWED == validationResult)
			removeMessage(request);
		if (ACCESS_ALLOWED == validationResult
				|| REMOVE_ALLOWED == validationResult) {

			getMessages(request, response);
		}
	}

	private void removeMessage(HttpServletRequest request) {
		String gmid = request.getParameter(PageConstants.GMID);

		HttpSession session = request.getSession(true);
		User sessionUser = (User) session.getAttribute(Messages.SESSION_USER);

		if (sessionUser != null && gmid != null) {
			MessageService msgService = new MessageService();
			Message msg = msgService.findById(new Integer(gmid));
			if (msg != null
					&& msg.getUserName().equals(sessionUser.getUserName()))
				msgService.deleteSingle(msg);
		}
	}

	/*
	 * Integer tempm_id=(Integer)tempm[0]; Integer tempm_tid=(Integer)tempm[1];
	 * String tempm_name=(String)tempm[2]; String *
	 * tempm_addtime=(String)tempm[3]; String tempm_userName=(String)tempm[4];
	 * Integer tempm_num=(Integer)tempm[5]; Integer tempm_up=(Integer)tempm[6];
	 * Integer tempm_flag=(Integer)tempm[7]; String tempm_tag=(String)tempm[8];
	 * String tempm_source=(String)tempm[9]; String
	 * tempm_stime=(String)tempm[10]; Integer
	 * commentNum=gmessdao.findCommentNum(tempm_id); Gcomment
	 * tmpG=gmessdao.findLastComment(tempm_id);
	 */
	private void getMessages(HttpServletRequest request,
			HttpServletResponse response) {
		int intpageid = 1;
		 
		String open = request.getParameter(PageConstants.OPEN);
		HttpSession session = request.getSession(true);
		User sessionUser = (User) session.getAttribute(Messages.SESSION_USER);
		MessageService msgService = new MessageService();
		long size = 0, intOpen = 2;
		long myInfoMsgSize = 0, myNav1MsgSize = 0, myCommunitiesMsgSize = 0, myNav2MsgSize = 0, myBookmarksMsgSize = 0, myRemindersMsgSize = 0;

		if (!PageConstants.ZERO.equals(Config.getConfig()
				.getProperty(Config.P1)))

			myInfoMsgSize = msgService.findSizeOfMessages(
					PageConstants.USERNAME, sessionUser.getUserName(),
					new Integer(1), 0);

		if (!PageConstants.ZERO.equals(Config.getConfig().getProperty(
				Config.P11)))
			myNav1MsgSize = msgService.findSizeOfMessages(
					PageConstants.USERNAME, sessionUser.getUserName(),
					new Integer(1), 1);
		if (!PageConstants.ZERO.equals(Config.getConfig()
				.getProperty(Config.P2)))
			myCommunitiesMsgSize = msgService.findSizeOfMessages(
					PageConstants.USERNAME, sessionUser.getUserName(),
					new Integer(2), 0);
		if (!PageConstants.ZERO.equals(Config.getConfig().getProperty(
				Config.P22)))
			myNav2MsgSize = msgService.findSizeOfMessages(
					PageConstants.USERNAME, sessionUser.getUserName(),
					new Integer(2), 1);
		if (!PageConstants.ZERO.equals(Config.getConfig()
				.getProperty(Config.P3)))
			myBookmarksMsgSize = msgService.findSizeOfMessages(
					PageConstants.USERNAME, sessionUser.getUserName(),
					new Integer(3));
		if (!PageConstants.ZERO.equals(Config.getConfig()
				.getProperty(Config.P4)))
			myRemindersMsgSize = msgService.findSizeOfMessages(
					PageConstants.USERNAME, sessionUser.getUserName(),
					new Integer(4));
	 
		request.setAttribute(INFO_MSG_SIZE, myInfoMsgSize);
		request.setAttribute(COMMUNITIES_MSG_SIZE, myCommunitiesMsgSize);
		request.setAttribute(BOOKMARKS_MSG_SIZE, myBookmarksMsgSize);
		request.setAttribute(REMINDERS_MSG_SIZE, myRemindersMsgSize);
		request.setAttribute(NAV1_MSG_SIZE, myNav1MsgSize);
		request.setAttribute(NAV2_MSG_SIZE, myNav2MsgSize);
		if (open == null) {
			if (size < myBookmarksMsgSize) {
				size = myBookmarksMsgSize;
				intOpen = 3;
			}
			if (size < myRemindersMsgSize) {
				size = myRemindersMsgSize;
				intOpen = 4;
			}
			if (size < myCommunitiesMsgSize) {
				size = myCommunitiesMsgSize;
				intOpen = 2;
			}
			if (size < myInfoMsgSize) {
				size = myInfoMsgSize;
				intOpen = 1;
			}
			request.setAttribute(PageConstants.OPEN, intOpen);
			open = Symbols.BLANK + intOpen;
		}

		String key = request.getParameter(KEY);

		String nav = request.getParameter(PageConstants.NAV);
		if (nav == null)
			nav = PageConstants.ZERO;
		int unit = 10;
		@SuppressWarnings("rawtypes")
		List msgs = null;
		long all = 0;
		int begin = 0, pagenums = 0;
		String pageid = request.getParameter(PageConstants.PAGEID);
		Integer openInteger = new Integer(open);
		if (pageid != null)
			intpageid = Integer.parseInt(pageid);
		if (key != null && !Symbols.BLANK.equals(key))
			all = msgService.searchSizeByPropertyAndUserName(
					PageConstants.NAME, key, sessionUser.getUserName());
		else {
			if (open != null && nav != null)
				all = msgService.findSizeOfMessages(PageConstants.USERNAME,
						sessionUser.getUserName(), openInteger,
						new Integer(nav));
			else if (open != null )
				all = msgService.findSizeOfMessages(PageConstants.USERNAME,
						sessionUser.getUserName(), openInteger);
		}
		pagenums = (int) ((all + unit - 1) / unit);
		begin = unit * (intpageid - 1);
		if (key != null && !Symbols.BLANK.equals(key))
			msgs = msgService.searchByPropertyAndUserName(PageConstants.NAME,
					key, sessionUser.getUserName(), begin, unit);
		else {

			if (open != null && nav != null)
				msgs = msgService.findMessages(PageConstants.USERNAME,
						sessionUser.getUserName(), openInteger,
						new Integer(nav), begin, unit);
			else if (open != null)
				msgs = msgService.findMessages(PageConstants.USERNAME,
						sessionUser.getUserName(), openInteger, begin, unit);
		}
		if (msgs == null)
			return;
		int startpid = intpageid - 3;
		if (startpid <= 0)
			startpid = 1;
		int endpid = intpageid + 8;
		if (intpageid > 8)
			endpid = intpageid + 6;
		if (endpid >= pagenums)
			endpid = pagenums;

		request.setAttribute(START_PID, startpid);
		request.setAttribute(END_PID, endpid);
		AttachmentService attachmentService = new AttachmentService();
		// comment count and time
		for (int k = 0; k < msgs.size(); k++) {
			Object[] tempm = (Object[]) msgs.get(k);
			Integer tempm_id = (Integer) tempm[0];
			Long commentNum = msgService.findCommentNum(tempm_id);
			Comment tmpG = msgService.findLastComment(tempm_id);
			request.setAttribute(tempm_id + COMMENT_NUM, commentNum);
			if (tmpG != null)
				request.setAttribute(tempm_id + LAST_COMMENT, tmpG.getTime());
			List<Attachment> attachments = attachmentService.findByProperty(
					PageConstants.GMID, tempm_id);

			if (attachments != null) {
				List<String> images = new ArrayList<String>();
				for (Attachment attachment : attachments) {
					String attached = attachment.getAttached();
					if (attached.endsWith("jpg") || attached.endsWith("JPG")
							|| attached.endsWith("gif")
							|| attached.endsWith("GIF")
							|| attached.endsWith("bmp")
							|| attached.endsWith("BMP")
							|| attached.endsWith("png")
							|| attached.endsWith("PNG"))
						images.add(attached);
				}
				request.setAttribute(tempm_id + "attachments", images);
			}
		}

		request.setAttribute(PageConstants.MSGS, msgs);
		request.setAttribute(PageConstants.PAGENUMS, pagenums);
		request.setAttribute(PageConstants.ALL, all);
		request.setAttribute(PageConstants.UNIT, unit);
		request.setAttribute(PageConstants.INTPAGEID, intpageid);

	}

	@Override
	public boolean isForward(int validationResult) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean enablePostLoad() {
		// TODO Auto-generated method stub
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see etcore.webapp.grouptalk.controller.action.AbstractAction#
	 * buildSelfContextAndAttributes(int, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public List<String> getNamespacesOfMessages(HttpServletRequest request) {
		// TODO Auto-generated method stub
		List<String> namespaces = new ArrayList<String>();
		namespaces.add(MessageNamespaces.MY_PROFILE);
		return namespaces;
	}

}
